from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from app.core.config import settings

# 添加连接池配置
engine = create_engine(
    settings.DATABASE_URL.replace('mysql://', 'mysql+pymysql://'),
    pool_size=5,  # 连接池大小
    max_overflow=10,  # 超过连接池大小外最多创建的连接
    pool_timeout=30,  # 连接池获取连接的超时时间
    pool_recycle=1800,  # 连接在连接池中重复使用的时间，超过后会被重置，防止连接失效
    pool_pre_ping=True,  # 每次连接前ping一下数据库，确保连接有效
    connect_args={
        "connect_timeout": 60,  # 连接超时时间
    }
)

SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

Base = declarative_base()

def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close() 